<?php

class SF_PromoteEvents_Helper_Data extends Mage_Core_Helper_Abstract
{
	protected $_eventCode = null;
	
    public function getEventsData()
    {
        if($this->_eventCode === null) return false;
    	return $eventsData	= Mage::getModel('promoteevents/events')->getCollection()
								->addFieldToFilter('event_code',$this->_eventCode)
								->getFirstItem();
								
    }
	
	public function getEvents($eventCode = null)
	{
		if($eventCode === null) return false; 
		$this->_eventCode = $eventCode;
		return $this;
	}
	
	public function getProducts($imgSize='200')
	{
		$eventsData = $this->getEventsData($this->_eventCode);
		$eventsId = $eventsData['id'];
		$eventsProductCollection = Mage::getModel('promoteevents/product')->getCollection()
								   ->addFieldToFilter('p_id', $eventsId)
								   ->addFieldToFilter('status', 1)
								   ->addFieldToFilter('is_recommand', 0);
		$eventsProductCollection->setOrder('priority', 'desc');
		$eventsProductCollection->setOrder('sort', 'desc');
		
		$productSkus = array();
		$products = array();
		$eventAllData = $eventsProductCollection->getData();
		
		foreach($eventAllData as $data)
		{
			$productSkus[$data['event_category_id']][] = $data['product_sku'];
		}
		
		foreach($productSkus as $key => $skus)
		{
			$_products = Mage::getResourceModel('catalog/product_collection')
						// ->addAttributeToSelect('*')
						->addAttributeToSelect('id')
						->addAttributeToSelect('name')
						->addUrlRewrite()
						->addAttributeToSelect('short_description')
						->addAttributeToSelect('thumbnail')
						->addAttributeToSelect('pirce')
						->addFinalPrice()
						->addAttributeToFilter('SKU', array('in' => $skus));
			Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($_products);
			Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_products); 
			$_products->getSelect()->joinLeft(
							array("rpep" => 'rumall_promote_events_product'),
							"e.sku = rpep.product_sku",
							array('priority','sort')
						)
						->where('rpep.p_id = '.$eventsId)
						->order('priority desc')
						->order('sort desc');
			foreach($_products as $product)
			{ 
			
				if($product->getTypeId() == 'simple')
				{
					$qtyStock = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
				}
				if($product->getTypeId() == 'configurable')
				{
					$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($product);
					$col = $conf->getUsedProductCollection()->addAttributeToSelect('status')->addFilterByRequiredOptions();
					$qtyStock = 0;
					foreach ($col as $sprod){
						if($sprod->getStatus() == '2') continue;
						$qty = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($sprod)->getQty());
						$qtyStock += $qty;
					}
				}
				
				$products[$key][] = array(
						'id'			 => $product->getId(),
						'sku'			 => $product->getSku(),
						'name'			 => $product->getName(),
						'url'			 => $product->getProductUrl(),
						'short_description'	=> $product->getShortDescription(),
						'wishlist'		 =>	Mage::helper('wishlist')->getAddUrl($product),
						'thumbnail'		 => (string)Mage::helper('catalog/image')->init($product, 'thumbnail')->resize($imgSize),
						'price'			 => $product->getPrice(),
						'currency_price' => Mage::helper('core')->currency($product->getPrice(), true, false),
						'final_price'    => $product->getFinalPrice(),
						'currency_final_price' => Mage::helper('core')->currency($product->getFinalPrice(), true, false),
						'qty'			 => $qtyStock,
						// 'available'		 => $product->isAvailable(),
					);
			}
			
		}
		return $products;
	}
	
	public function getRecommandProducts($imgSize='200')
	{
		$eventsData = $this->getEventsData($this->_eventCode);
		$eventsId = $eventsData['id'];
		$eventsProductCollection = Mage::getModel('promoteevents/product')->getCollection()
								   ->addFieldToFilter('p_id', $eventsId)
								   ->addFieldToFilter('status', 1)
								   ->addFieldToFilter('is_recommand', 1);
		$eventsProductCollection->setOrder('priority', 'desc');
		$eventsProductCollection->setOrder('sort', 'desc');
		
		$productSkus = array();
		$products = array();
		$eventAllData = $eventsProductCollection->getData();
		
		foreach($eventAllData as $data)
		{
			$productSkus[$data['event_category_id']][] = $data['product_sku'];
		}
		
		foreach($productSkus as $key => $skus)
		{
			$_products = Mage::getResourceModel('catalog/product_collection')
						// ->addAttributeToSelect('*')
						->addAttributeToSelect('id')
						->addAttributeToSelect('name')
						->addUrlRewrite()
						->addAttributeToSelect('short_description')
						->addAttributeToSelect('thumbnail')
						->addAttributeToSelect('pirce')
						->addFinalPrice()
						->addAttributeToFilter('SKU', array('in' => $skus));
			Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($_products);
			Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_products); 
			$_products->getSelect()->joinLeft(
							array("rpep" => 'rumall_promote_events_product'),
							"e.sku = rpep.product_sku",
							array('priority','sort')
						)
						->where('rpep.p_id = '.$eventsId)
						->order('priority desc')
						->order('sort desc');
			foreach($_products as $product)
			{
				if($product->getTypeId() == 'simple')
				{
					$qtyStock = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
				}
				if($product->getTypeId() == 'configurable')
				{
					$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($product);
					$col = $conf->getUsedProductCollection()->addAttributeToSelect('status')->addFilterByRequiredOptions();
					$qtyStock = 0;
					foreach ($col as $sprod){
						if($sprod->getStatus() == '2') continue;
						$qty = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($sprod)->getQty());
						$qtyStock += $qty;
					}
				}
			
			
				$products[$key][] = array(
						'id'			 => $product->getId(),
						'sku'			 => $product->getSku(),
						'name'			 => $product->getName(),
						'url'			 => $product->getProductUrl(),
						'short_description'	=> $product->getShortDescription(),
						'wishlist'		 =>	Mage::helper('wishlist')->getAddUrl($product),
						'thumbnail'		 => (string)Mage::helper('catalog/image')->init($product, 'thumbnail')->resize($imgSize),
						'price'			 => $product->getPrice(),
						'currency_price' => Mage::helper('core')->currency($product->getPrice(), true, false),
						'final_price'    => $product->getFinalPrice(),
						'currency_final_price' => Mage::helper('core')->currency($product->getFinalPrice(), true, false),
						'qty'			 => $qtyStock,
						// 'available'		 => $product->isAvailable(),
					);
			
			}
		}
		return $products;
	}
	
	
	public function getCategoryTitle()
	{
		$currentStore = Mage::app()->getStore()->getStoreId();
		$eventsTitle = array();
		if($currentStore != 2){
			$eventsCategory = Mage::getModel('promoteevents/category')->getCollection()
									->addFieldToSelect('id')
									->addFieldToSelect('category_title_en');
			foreach($eventsCategory->getData() as $val){$eventTitle[$val['id']] = $val['category_title_en'];}
			return $eventTitle;
		}else{
			$eventsCategory = Mage::getModel('promoteevents/category')->getCollection()
									->addFieldToSelect('id')
									->addFieldToSelect('category_title_ru');
			foreach($eventsCategory->getData() as $val){$eventTitle[$val['id']] = $val['category_title_ru'];}
			return $eventTitle;
		}
	}
	
	public function getEventsFromDate()
	{
		$eventsData = $this->getEventsData($this->_eventCode);
		if($eventsData){
			return $eventsData['from_date'];
		}else{
			return false;
		}
		
	}
	
	public function getEventsToDate()
	{
		$eventsData = $this->getEventsData($this->_eventCode);
		if($eventsData){
			return $eventsData['to_date'];
		}else{
			return false;
		}
	}
	
	
	public function getCurrentStcok($productId)
	{
		$_product = Mage::getModel('catalog/product')->load($productId);
		if($_product->getTypeId() == 'simple')
		{
			$qtyStock = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
			return $qtyStock;
		}
		if($_product->getTypeId() == 'configurable')
		{
			$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
			$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
			$qtyStock = 0;
			foreach ($col as $sprod){
				if(!$sprod->isAvailable()) continue;
				$qty = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($sprod)->getQty());
				$qtyStock += $qty;
			}
			return $qtyStock;
		}
		return null;
	}
	
	public function isNeedShowStock($_product)
	{
		$sku = $_product->getSku();
		$rs = Mage::getModel('promoteevents/product')->getCollection()->addFieldToFilter('product_sku', $sku);
		if($rs->getData()){
			return true;
		}else{
			return false;
		}
	}
	
	public function isDisplayLabels($productId)
	{
		$_product = Mage::getModel('catalog/product')->load($productId);
		$this->_display($_product);
	}
	
	function _initLabels()
    {
        if($this->labels)
            return $this->labels;
		$collection = Mage::getModel('productlabels/productlabels')->getCollection()->setStoreId(Mage::app()->getStore()->getId())
					->addAttributeToFilter('status',1)
					->addAttributeToSelect('*');
        $this->labels = $collection;
        return $this->labels;
    }

    function _display($_product)
    {
        $labels = $this->_initLabels();
        $block = new EM_Productlabels_Block_Productlabels();
        $labelShows = array();
        foreach ($labels as $label)
        {
            $catalogRule = Mage::getModel('productlabels/rule');
            $actionsArr = unserialize($label->getActions());
            if (!empty($actionsArr) && is_array($actionsArr)) {
                $catalogRule->getConditions()->loadArray($actionsArr);
            }
            $object = new Varien_Object();
            $object->setData('product', $_product);
            $object->setData('label', $label);
            
            if($validate = (bool)$catalogRule->validate($object)){
                $labelShows[] = $label;
            }
        }
        if(!empty ($labelShows)){
            echo $block->addObject(array('labels'=>$labelShows,'product'=>$_product))
			           ->setTemplate('em_productlabels/productlabels.phtml')->toHtml();
        }	
    }
	
	
	
}